package com.telecom.sxint.app.api.controller.SystemController.App1SystemFileController;

import cn.zjtele.pubinfo.common.http.response.ResponseData;
import com.telecom.sxint.app.core.domain.entity.Systempojo.App1YunwangWorkpojo.App1YunwangWorkEvaluationIndicatorsData;
import com.telecom.sxint.app.core.domain.entity.dto.AnalyseDateDTO;
import com.telecom.sxint.app.core.domain.entity.dto.EvaluationIndicatorsDTO;
import com.telecom.sxint.app.core.service.Systemservice.App1YunwangWorkservice.IApp1YunwangWorkEvaluationIndicatorsDataService;
import com.telecom.sxint.app.core.service.Systemservice.App1YunwangWorkservice.IApp1YunwangWorkEvaluationIndicatorsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc.*;

/**
 * 分析word导出控制器
 */
@RestController
@Tag(name = "分析word导出控制器", description = "分析word导出控制器")
@RequestMapping("/app1-system")
public class App1SystemanalyFilexport {
    /**
     * 导出雷达word模板
     */
    @Autowired
    private IApp1YunwangWorkEvaluationIndicatorsDataService app1YunwangWorkEvaluationIndicatorsDataService;
    @Autowired
    private IApp1YunwangWorkEvaluationIndicatorsService app1YunwangWorkEvaluationIndicatorsService;
    @Operation(summary = "导出雷达word模板", description = "导出word模板")
    @GetMapping("/exportWord")
    public  ResponseEntity<ByteArrayResource> exportWordDocument() throws IOException {
        // 创建Word文档
        XWPFDocument document = new XWPFDocument();

        // 添加标题
        XWPFParagraph titleParagraph = document.createParagraph();
        XWPFRun titleRun = titleParagraph.createRun();
        titleRun.setText("2024年6月区县云网工作评价体系雷达图");

        // 添加一级标题
        XWPFParagraph firstLevelTitle1 = document.createParagraph();
        XWPFRun firstLevelTitle1Run = firstLevelTitle1.createRun();
        firstLevelTitle1Run.setText("一、按考核项目");

        // 添加一级标题
        XWPFParagraph firstLevelTitle2 = document.createParagraph();
        XWPFRun firstLevelTitle2Run = firstLevelTitle2.createRun();
        firstLevelTitle2Run.setText("二、按区县");

        // 将文档写入到ByteArrayOutputStream中
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        document.write(baos);
        byte[] bytes = baos.toByteArray();
        document.close();

        // 创建ByteArrayResource，用于作为响应体
        ByteArrayResource resource = new ByteArrayResource(bytes) {
            @Override
            public String getFilename() {
                return "wordTemplate.docx";
            }
        };

        // 设置HTTP响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"");

        // 返回响应实体
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

    /**
     * 导出云网word模板
     * @return
     * @throws IOException
     */
    @Operation(summary = "导出云网word模板", description = "导出word模板")
    @GetMapping("/exportWord1")
    public ResponseEntity<ByteArrayResource> exportWord() throws IOException {
        //变量
        double total = 0,totalYueCheng = 0,totalKeqiao =0,totalShangYu = 0,totalShengZhou = 0,totalXinChang = 0,totalZhuJi = 0;
        int rankYueCheng = 0,rankKeqiao = 0,rankShangYu = 0,rankShengZhou = 0,rankXinChang = 0,rankZhuJi = 0;
        // 创建Word文档
        XWPFDocument document = new XWPFDocument();

        // 添加标题
        XWPFParagraph titleParagraph = document.createParagraph();
        XWPFRun titleRun = titleParagraph.createRun();
        titleRun.setText("一、2024年6月区县云网工作评价体系得分如下：");

        //获取数据
        List<EvaluationIndicatorsDTO> list = app1YunwangWorkEvaluationIndicatorsService.selectWithData();

        //创建表格
        XWPFTable table = document.createTable(1,9);
        // 设置表格宽度为100%
        table.setWidth("100%");
        //创建标题行
        XWPFTableRow titleRow = table.getRow(0);
        titleRow.getCell(0).setText("考核项目");
        titleRow.getCell(1).setText("大指标");
        titleRow.getCell(2).setText("大指标分值");
        titleRow.getCell(3).setText("越城");
        titleRow.getCell(4).setText("柯桥");
        titleRow.getCell(5).setText("上虞");
        titleRow.getCell(6).setText("嵊州");
        titleRow.getCell(7).setText("新昌");
        titleRow.getCell(8).setText("诸暨");
        //设置文本居中和单元格宽度
        for (int i = 0; i < 9; i++) {
            titleRow.getCell(i).getCTTc().addNewTcPr().addNewVAlign().setVal(STVerticalJc.CENTER);
            if (i == 0 || i == 1){
                titleRow.getCell(i).setWidth("15%");
            }else {
                titleRow.getCell(i).setWidth("10%");
            }
        }
        String previousEvaluationItem = "";
        int rowIndex = 1;
        int count = 1;

//添加数据行
        for (EvaluationIndicatorsDTO data:list){


            XWPFTableRow dataRow = table.createRow();
            dataRow.getCell(0).setText(data.getEvaluationItem());
            dataRow.getCell(1).setText(data.getMainIndicator());
            dataRow.getCell(2).setText(data.getDataProvisionDepartment());
            dataRow.getCell(3).setText(data.getYuecheng());
            dataRow.getCell(4).setText(data.getKeqiao());
            dataRow.getCell(5).setText(data.getShangyu());
            dataRow.getCell(6).setText(data.getShengzhou());
            dataRow.getCell(7).setText(data.getXinchang());
            dataRow.getCell(8).setText(data.getZhuji());

            //设置居中
            for (int i = 0; i < 9; i++) {
                dataRow.getCell(i).getCTTc().addNewTcPr().addNewVAlign().setVal(STVerticalJc.CENTER);
                if (i == 0 || i == 1){
                    dataRow.getCell(i).setWidth("15%");
                }else {
                    dataRow.getCell(i).setWidth("10%");
                }
            }

            //计算
            DecimalFormat df = new DecimalFormat("#.00");
            if (!data.getYuecheng().isEmpty()) {
                totalYueCheng += Double.parseDouble(df.format(Double.parseDouble(data.getYuecheng())));
            }
            if (!data.getKeqiao().isEmpty()) {
                totalKeqiao += Double.parseDouble(df.format(Double.parseDouble(data.getKeqiao())));
            }
            if (!data.getShangyu().isEmpty()) {
                totalShangYu += Double.parseDouble(df.format(Double.parseDouble(data.getShangyu())));
            }
            if (!data.getShengzhou().isEmpty()) {
                totalShengZhou += Double.parseDouble(df.format(Double.parseDouble(data.getShengzhou())));
            }
            if (!data.getXinchang().isEmpty()) {
                totalXinChang += Double.parseDouble(df.format(Double.parseDouble(data.getXinchang())));
            }
            if (!data.getZhuji().isEmpty()) {
                totalZhuJi += Double.parseDouble(df.format(Double.parseDouble(data.getZhuji())));
            }


            if (previousEvaluationItem!=null && previousEvaluationItem.equals(data.getEvaluationItem())){
                if (count == 1){
                    XWPFTableCell cellToMerge = table.getRow(rowIndex).getCell(0);
                    cellToMerge.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
                    XWPFTableCell cellBelow = table.getRow(rowIndex - 1).getCell(0);
                    cellBelow.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
                    count++;
                }else {
                    XWPFTableCell cellBelow = table.getRow(rowIndex).getCell(0);
                    cellBelow.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
                }

            }else {
                count = 1;
            }
            previousEvaluationItem = data.getEvaluationItem();
            rowIndex++;
        }


        //合计
        DecimalFormat df = new DecimalFormat("#.00");
        XWPFTableRow dataRow = table.createRow();
        dataRow.getCell(0).setText("合计");
        dataRow.getCell(0).getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
        dataRow.getCell(1).getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
        dataRow.getCell(2).setText(String.valueOf(100.00));
        dataRow.getCell(3).setText(String.valueOf(df.format(totalYueCheng)));
        dataRow.getCell(4).setText(String.valueOf(totalKeqiao));
        dataRow.getCell(5).setText(String.valueOf(totalShangYu));
        dataRow.getCell(6).setText(String.valueOf(df.format(totalShengZhou)));
        dataRow.getCell(7).setText(String.valueOf(df.format(totalXinChang)));
        dataRow.getCell(8).setText(String.valueOf(totalZhuJi));
        //设置文本居中和单元格宽度
        for (int i = 0; i < 9; i++) {
            dataRow.getCell(i).getCTTc().addNewTcPr().addNewVAlign().setVal(STVerticalJc.CENTER);
            if (i == 0 || i == 1){
                dataRow.getCell(i).setWidth("15%");
            }else {
                dataRow.getCell(i).setWidth("10%");
            }
        }
//
        Map<String, Double> scores = new HashMap<>();
        scores.put("totalYueCheng", totalYueCheng);
        scores.put("totalKeqiao", totalKeqiao);
        scores.put("totalShangYu", totalShangYu);
        scores.put("totalShengZhou", totalShengZhou);
        scores.put("totalXinChang", totalXinChang);
        scores.put("totalZhuJi", totalZhuJi);
        // 将Map转换为List，并对其进行排序
        List<Map.Entry<String, Double>> entryList = new ArrayList<>(scores.entrySet());
        Collections.sort(entryList, new Comparator<Map.Entry<String, Double>>() {
            @Override
            public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) {
                return o2.getValue().compareTo(o1.getValue()); // 降序排序
            }
        });
        int rank = 1;
        for (Map.Entry<String, Double> entry : entryList) {
            if (entry.getKey().equals("totalYueCheng")) rankYueCheng = rank;
            if (entry.getKey().equals("totalKeqiao")) rankKeqiao = rank;
            if (entry.getKey().equals("totalShangYu")) rankShangYu = rank;
            if (entry.getKey().equals("totalShengZhou")) rankShengZhou = rank;
            if (entry.getKey().equals("totalXinChang")) rankXinChang = rank;
            if (entry.getKey().equals("totalZhuJi")) rankZhuJi = rank;
            rank++;
        }
        XWPFTableRow dataRow1 = table.createRow();
        dataRow1.getCell(0).setText("排名");
        dataRow1.getCell(0).getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
        dataRow1.getCell(1).getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
        dataRow1.getCell(2).setText(String.valueOf(""));
        dataRow1.getCell(3).setText(String.valueOf(rankYueCheng));
        dataRow1.getCell(4).setText(String.valueOf(rankKeqiao));
        dataRow1.getCell(5).setText(String.valueOf(rankShangYu));
        dataRow1.getCell(6).setText(String.valueOf(rankShengZhou));
        dataRow1.getCell(7).setText(String.valueOf(rankXinChang));
        dataRow1.getCell(8).setText(String.valueOf(rankZhuJi));
        //设置文本居中和单元格宽度
        for (int i = 0; i < 9; i++) {
            dataRow1.getCell(i).getCTTc().addNewTcPr().addNewVAlign().setVal(STVerticalJc.CENTER);
            if (i == 0 || i  == 1){
                dataRow1.getCell(i).setWidth("15%");
            }else {
                dataRow1.getCell(i).setWidth("10%");
            }
        }


        // 删除空的标题行（如果数据为空）
        if (table.getRows().size() == 1) {
            table.removeRow(0);
        }


        // 添加一级标题
        XWPFParagraph firstLevelTitle1 = document.createParagraph();
        XWPFRun firstLevelTitle1Run = firstLevelTitle1.createRun();
        firstLevelTitle1Run.setText("二、总体情况及得分细项");



        // 将文档写入到ByteArrayOutputStream中
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        document.write(baos);
        byte[] bytes = baos.toByteArray();
        document.close();

        // 创建ByteArrayResource，用于作为响应体
        ByteArrayResource resource = new ByteArrayResource(bytes) {
            @Override
            public String getFilename() {
                return "wordTemplate.docx";
            }
        };

        // 设置HTTP响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"");

        // 返回响应实体
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }
    /**
     * 获取分析数据
     * @return
     * @throws
     */
    @Operation(summary = "分析数据获取", description = "获取分析数据")
    @GetMapping("/getData")
    public ResponseData<List<AnalyseDateDTO>> getData() throws Exception {
        List<AnalyseDateDTO> data = app1YunwangWorkEvaluationIndicatorsService.selectAnalyseDateWithData();

        // 使用Collectors.toMap进行分组和合并
        Map<String, AnalyseDateDTO> groupedData = data.stream()
                .collect(Collectors.toMap(
                        AnalyseDateDTO::getEvaluationItem, // 作为key的函数
                        Function.identity(), // 作为value的函数
                        (thisDTO, otherDTO) -> {
                            // 如果有相同的evaluationItem，则合并它们
                            thisDTO.mergeWith(otherDTO);
                            return thisDTO;
                        }
                ));

        // 将Map的值转换回List
        List<AnalyseDateDTO> compressedData = new ArrayList<>(groupedData.values());

        return ResponseData.success(compressedData);
    }


}
